<template>
  <div class="profile-center-container">
    <div class="profile-center">
      <!-- 头部信息 -->
      <div class="profile-header">
        <div class="avatar-section">
          <el-avatar :size="120" :src="userInfo.avatar" class="user-avatar">
            <img src="https://picsum.photos/120" alt="默认头像"/>
          </el-avatar>
          <el-upload
            class="avatar-upload"
            action="#"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :http-request="handleAvatarUpload"
          >
            <el-button type="danger" plain round>
              <el-icon><Upload /></el-icon>更换头像
            </el-button>
          </el-upload>
        </div>
        <div class="user-info">
          <h1 class="username">{{ userInfo.username }}</h1>
          <p class="meta-info">
            <el-icon><User /></el-icon> 注册时间：{{ formatDate(userInfo.createTime) }}
          </p>
          <p class="meta-info">
            <el-icon><Message /></el-icon> 邮箱：{{ userInfo.email || '未绑定' }}
          </p>
        </div>
      </div>

      <!-- 功能导航 -->
      <el-tabs v-model="activeTab" class="profile-tabs">
        <!-- 基本信息 -->
        <el-tab-pane label="基本信息" name="basic">
          <el-form
            :model="userInfo"
            :rules="formRules"
            label-width="100px"
            class="profile-form"
            label-position="left"
          >
            <el-row :gutter="30">
              <el-col :xs="24" :sm="12">
                <el-form-item label="用户名" prop="username">
                  <el-input
                    v-model="userInfo.username"
                    placeholder="请输入用户名"
                    clearable
                  />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12">
                <el-form-item label="真实姓名" prop="realName">
                  <el-input
                    v-model="userInfo.realName"
                    placeholder="请输入真实姓名"
                    clearable
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="30">
              <el-col :xs="24" :sm="12">
                <el-form-item label="性别" prop="gender">
                  <el-select
                    v-model="userInfo.gender"
                    placeholder="请选择性别"
                    clearable
                  >
                    <el-option label="男" value="male" />
                    <el-option label="女" value="female" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12">
                <el-form-item label="出生日期" prop="birthday">
                  <el-date-picker
                    v-model="userInfo.birthday"
                    type="date"
                    placeholder="选择出生日期"
                    value-format="YYYY-MM-DD"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="30">
              <el-col :xs="24" :sm="12">
                <el-form-item label="联系电话" prop="phone">
                  <el-input
                    v-model="userInfo.phone"
                    placeholder="请输入手机号码"
                    clearable
                  >
                    <template #prefix>
                      <el-icon><Iphone /></el-icon>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12">
                <el-form-item label="所在地区" prop="region">
                  <elui-china-area-dht @change="onChange" style="width: 100%"></elui-china-area-dht>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="电子邮箱" prop="email">
              <el-input
                v-model="userInfo.email"
                placeholder="请输入邮箱"
                clearable
              >
                <template #prefix>
                  <el-icon><Message /></el-icon>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item label="个人简介" prop="bio">
              <el-input
                v-model="userInfo.bio"
                type="textarea"
                :rows="4"
                maxlength="200"
                show-word-limit
                placeholder="介绍一下自己..."
                resize="vertical"
              />
            </el-form-item>

            <el-form-item>
              <el-button
                type="danger"
                @click="saveProfile"
                :loading="saving"
                size="large"
              >
                <el-icon v-if="!saving"><Check /></el-icon>
                {{ saving ? '保存中...' : '保存修改' }}
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 安全设置 -->
        <el-tab-pane label="安全设置" name="security">
          <el-form
            :model="securityForm"
            :rules="securityRules"
            class="security-form"
            label-width="100px"
            label-position="left"
          >
            <el-form-item label="原密码" prop="oldPassword">
              <el-input
                v-model="securityForm.oldPassword"
                type="password"
                show-password
                placeholder="请输入当前密码"
              />
            </el-form-item>

            <el-form-item label="新密码" prop="newPassword">
              <el-input
                v-model="securityForm.newPassword"
                type="password"
                show-password
                placeholder="6-20位字母、数字或符号"
              />
            </el-form-item>

            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input
                v-model="securityForm.confirmPassword"
                type="password"
                show-password
                placeholder="请再次输入新密码"
              />
            </el-form-item>

            <el-form-item>
              <el-button
                type="danger"
                @click="changePassword"
                :loading="changingPassword"
                size="large"
              >
                <el-icon v-if="!changingPassword"><Lock /></el-icon>
                {{ changingPassword ? '修改中...' : '确认修改' }}
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 账户管理 -->
        <el-tab-pane label="账户管理" name="account">
          <div class="danger-zone">
            <h3 class="danger-title"><el-icon><Warning /></el-icon> 危险操作区</h3>

            <div class="danger-item">
              <div class="danger-content">
                <span class="danger-label">注销账户</span>
                <p class="danger-desc">永久删除账户及所有数据，操作不可逆</p>
              </div>
              <el-button
                type="danger"
                plain
                @click="showConfirmDialog('deleteAccount')"
              >
                立即注销
              </el-button>
            </div>

            <div class="danger-item">
              <div class="danger-content">
                <span class="danger-label">退出登录</span>
                <p class="danger-desc">退出当前登录状态，返回登录页面</p>
              </div>
              <el-button
                type="danger"
                plain
                @click="showConfirmDialog('logout')"
              >
                立即退出
              </el-button>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>

      <!-- 确认对话框 -->
      <el-dialog
        v-model="confirmDialog.visible"
        :title="confirmDialog.title"
        width="30%"
      >
        <span>{{ confirmDialog.content }}</span>
        <template #footer>
          <el-button @click="confirmDialog.visible = false">取消</el-button>
          <el-button type="danger" @click="handleConfirmAction">
            确认
          </el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  User,
  Message,
  Upload,
  Warning,
  Iphone,
  Check,
  Lock
} from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
import { EluiChinaAreaDht } from 'elui-china-area-dht'

dayjs.locale('zh-cn')

interface UserInfo {
  username: string
  realName: string
  email: string
  avatar: string
  bio: string
  createTime: number
  gender: string
  region: string[]
  phone: string
  birthday: string
}

interface SecurityForm {
  oldPassword: string
  newPassword: string
  confirmPassword: string
}

const router = useRouter()

// 用户信息
const userInfo = reactive<UserInfo>({
  username: '未命名用户',
  realName: '',
  email: 'user@example.com',
  avatar: '',
  bio: '',
  createTime: Date.now(),
  gender: '',
  region: [],
  phone: '',
  birthday: ''
})

// 安全设置表单
const securityForm = reactive<SecurityForm>({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const chinaData = new EluiChinaAreaDht.ChinaArea().chinaAreaflat

// 覆盖区县
const onChange = (e: any) => {
    const province = chinaData[e[0]]
    const city = chinaData[e[1]]
    const area = chinaData[e[2]]
    console.log(province, city, area)
}

// 表单验证规则
const formRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 16, message: '用户名长度2-16个字符', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5]{2,10}$/, message: '请输入有效中文姓名', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
  ],
  birthday: [
    { required: true, message: '请选择出生日期', trigger: 'change' }
  ],
  region: [
    { required: true, message: '请选择所在地区', trigger: 'change' }
  ]
}

const securityRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度6-20位', trigger: 'blur' },
    { pattern: /^(?=.*[a-zA-Z])(?=.*\d).+$/, message: '需包含字母和数字', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value !== securityForm.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 页面状态
const activeTab = ref('basic')
const saving = ref(false)
const changingPassword = ref(false)
const confirmDialog = reactive({
  visible: false,
  actionType: '',
  title: '',
  content: ''
})

// 初始化加载用户数据
onMounted(() => {
  loadUserData()
})

const loadUserData = () => {
  const savedData = localStorage.getItem('userProfile')
  if (savedData) {
    Object.assign(userInfo, JSON.parse(savedData))
  }
}

// 日期格式化
const formatDate = (timestamp: number) => {
  return dayjs(timestamp).format('YYYY年MM月DD日 HH:mm')
}

// 头像上传处理
const beforeAvatarUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过2MB')
    return false
  }
  return true
}

const handleAvatarUpload = async ({ file }: { file: File }) => {
  try {
    const reader = new FileReader()
    reader.onload = (e) => {
      if (e.target?.result) {
        userInfo.avatar = e.target.result as string
        saveProfile()
      }
    }
    reader.readAsDataURL(file)
  } catch (error) {
    ElMessage.error('头像上传失败')
  }
}

// 保存个人资料
const saveProfile = async () => {
  try {
    saving.value = true
    await new Promise(resolve => setTimeout(resolve, 800)) // 模拟API请求
    localStorage.setItem('userProfile', JSON.stringify(userInfo))
    ElMessage.success('个人信息保存成功')
  } catch (error) {
    ElMessage.error('保存失败，请重试')
  } finally {
    saving.value = false
  }
}

// 修改密码
const changePassword = async () => {
  try {
    changingPassword.value = true
    await new Promise(resolve => setTimeout(resolve, 1000)) // 模拟API请求
    securityForm.oldPassword = ''
    securityForm.newPassword = ''
    securityForm.confirmPassword = ''
    ElMessage.success('密码修改成功')
  } catch (error) {
    ElMessage.error('密码修改失败')
  } finally {
    changingPassword.value = false
  }
}

// 账户操作相关
const showConfirmDialog = (type: string) => {
  confirmDialog.actionType = type
  confirmDialog.title = type === 'logout' ? '确认退出登录' : '确认注销账户'
  confirmDialog.content = type === 'logout'
    ? '确定要退出当前登录状态吗？'
    : '此操作将永久删除账户，是否继续？'
  confirmDialog.visible = true
}

const handleConfirmAction = () => {
  confirmDialog.visible = false
  if (confirmDialog.actionType === 'logout') {
    handleLogout()
  } else {
    handleAccountDeletion()
  }
}

const handleLogout = () => {
  localStorage.removeItem('token')
  router.push('/login')
  ElMessage.success('已退出登录')
}

const handleAccountDeletion = () => {
  ElMessageBox.confirm('此操作将永久删除账户，请谨慎操作', '最后确认', {
    confirmButtonText: '确认删除',
    cancelButtonText: '取消',
    type: 'error',
    confirmButtonClass: 'el-button--danger'
  }).then(() => {
    localStorage.removeItem('userProfile')
    router.push('/login')
    ElMessage.success('账户已注销')
  })
}
</script>

<style lang="scss" scoped>
.profile-center-container {

  .profile-center {
    max-width: 1200px;
    margin: 0 auto;
    padding: 10px;
  }

  .profile-header {
    display: flex;
    align-items: center;
    padding: 20px;
    border-radius: 12px;
    border: 1px solid var(--el-color-danger);
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
    margin-bottom: 10px;

    .avatar-section {
      text-align: center;
      margin-right: 60px;

      .user-avatar {
        margin-bottom: 20px;
        border: 2px solid var(--el-color-danger);
        padding: 4px;
      }

      .avatar-upload {
        .el-button {
          padding: 10px 20px;
        }
      }
    }

    .user-info {
      flex: 1;
      .username {
        margin: 0 0 16px;
        color: var(--el-text-color-primary);
        font-size: 28px;
      }

      .meta-info {
        color: var(--el-text-color-secondary);
        margin: 12px 0;
        display: flex;
        align-items: center;
        font-size: 14px;

        .el-icon {
          margin-right: 8px;
          font-size: 18px;
        }
      }
    }
  }

  .profile-tabs {
    border-radius: 12px;
    padding: 10px;
    border: 1px solid var(--el-color-danger);
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);

    :deep(.el-tabs__header) {
      margin: 0 0 10px;
    }

    :deep(.el-tabs__nav-wrap),
    .profile-form,
    .security-form {
      max-width: 800px;
      margin: 0 auto;

      :deep(.el-form-item__label) {
        font-weight: 500;
        color: var(--el-text-color-primary);
      }

      .el-input,
      .el-select,
      .el-cascader,
      .el-date-editor {
        width: 100%;
      }

      .el-button {
        padding: 12px 28px;
        .el-icon {
          margin-right: 8px;
        }
      }
    }

    .security-form {
      :deep(.el-input__prefix) {
        display: flex;
        align-items: center;
      }

      .password-strength {
        margin-top: 8px;
        font-size: 12px;

        &.weak { color: var(--el-color-danger) }
        &.medium { color: var(--el-color-warning) }
        &.strong { color: var(--el-color-success) }
      }
    }

    .danger-zone {
      padding: 24px;
      border-radius: 8px;
      background: var(--el-color-danger-light-9);

      .danger-title {
        color: var(--el-color-danger);
        margin-bottom: 20px;
        display: flex;
        align-items: center;

        .el-icon {
          margin-right: 10px;
          font-size: 20px;
        }
      }

      .danger-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 16px;
        margin-bottom: 16px;
        border: 1px solid var(--el-color-danger);
        border-radius: 6px;
        transition: box-shadow 0.3s;

        &:hover {
          box-shadow: 0 2px 12px rgba(255, 77, 79, 0.1);
        }

        .danger-content {
          .danger-label {
            font-weight: 500;
            color: var(--el-text-color-primary);
          }

          .danger-desc {
            color: var(--el-text-color-secondary);
            font-size: 13px;
            margin-top: 4px;
          }
        }

        .el-button {
          flex-shrink: 0;
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .profile-center-container {
    padding: 0;

    .profile-header {
      flex-direction: column;
      padding: 24px;
      text-align: center;

      .avatar-section {
        margin: 0 0 20px;
      }

      .user-info {
        .username {
          font-size: 24px;
        }
      }
    }

    .profile-tabs {
      padding: 16px;

      :deep(.el-tabs__nav-wrap) {
        overflow-x: auto;
      }

      .profile-form,
      .security-form {
        .el-col {
          margin-bottom: 18px;
        }
      }

      .danger-item {
        flex-direction: column;
        align-items: flex-start;
        gap: 12px;

        .el-button {
          width: 100%;
        }
      }
    }
  }
}

@media (max-width: 480px) {
  .profile-center-container {
    .profile-header {
      .avatar-section {
        .user-avatar {
          width: 80px;
          height: 80px;
        }
      }
    }

    .profile-tabs {
      :deep(.el-tabs__item) {
        padding: 0 12px;
      }
    }
  }
}
</style>
